<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 消息提示 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false">
      </el-alert>
      <!-- Steps步骤条 -->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px"
        label-position="top">
        <el-tabs :tab-position="tabPosition" v-model="activeIndex"
        :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <!-- name的值会绑定给v-model绑定的属性 -->
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addForm.goods_cat" :options="catesList" :props="cateProps"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染每项参数 -->
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- checkbox渲染每项参数中的attr_vals值 -->
              <el-checkbox-group v-model="item.attr_vals">
                <!-- 将参数中每项渲染 -->
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染每项属性 -->
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="imgURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"/>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>
    <!-- 图片预览框 -->
    <el-dialog title="图片预览" :visible.sync="imgDialogVisible" width="30%">
      <img :src="imgPreview">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // Steps中哪个高亮显示
      activeIndex: '0',
      // 控制tab标签位置
      tabPosition: 'left',
      // 表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 接收商品分类的选项值
        goods_cat: [],
        // 图片临时路径
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品的参数和属性数组
        attrs: []
      },
      // 验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      // 商品分类
      catesList: [],
      // 级联选择器props配置
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id' // 指定每个选项的值
      },
      // 接收商品动态参数
      manyTableData: [],
      // 接收静态属性
      onlyTableData: [],
      // 图片上传到的后台地址：
      imgURL: 'http://timemeetyou.com:8889/api/private/v1/upload',
      // 设置上传时的请求头
      headerObj: {
        // 请求头中添加authorization字段，属性值为token
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览框
      imgDialogVisible: false,
      // 图片预览路径
      imgPreview: ''
    }
  },
  created () {
    this.getCatesList()
  },
  methods: {
    // 获取商品分类
    async getCatesList () {
      const { data: res } = await this.$http.get('categories/')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      console.log(res.data)
      this.catesList = res.data
    },
    // 级联选择器选项改变时触发
    handleChange () {
      console.log(this.addForm.goods_cat)
      // 如果选中的不是三级分类则无效
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // tab切换时触发
    beforeTabLeave (next, old) {
      // 在name为0的tab标签页中没选择商品分类时
      if (old === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // tab选中时触发,获取商品参数
    async tabClicked () {
      // 当选中的tab标签页为商品参数时
      if (this.activeIndex === '1') {
        // 发送请求
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }
        // 将参数中的attr_vals变为数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data

        console.log(this.manyTableData)
      } else if (this.activeIndex === '2') {
        // 发送请求
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
          { params: { sel: 'only' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品属性失败')
        }
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 图片预览时触发
    handlePreview (file) {
      console.log(file)
      // 获取图片url
      this.imgPreview = file.response.data.url
      this.imgDialogVisible = true
    },
    // 删除图片时触发
    handleRemove (file) {
      // 获取删除的路径
      const removePath = file.response.data.tmp_path
      // 在pics中找到相同tmp_path的值,获取索引值
      const i = this.addForm.pics.findIndex(
        item => item.pic === removePath
      )
      // 删除pics中此索引的值
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 上传成功时,接受一个服务端传过来的数据
    handleSuccess (response) {
      console.log(response)
      // 拼接一个路径对象
      const urlObj = { pic: response.data.tmp_path }
      // 将此路径对象push到pics数组中
      this.addForm.pics.push(urlObj)
      console.log(this.addForm)
    },
    // 添加商品
    add () {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的商品信息')
        }
        // 深拷贝表单数据对象
        const form = this.$deepClone(this.addForm)
        // 将表单数据对象中的goods_cate改为字符串
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const manyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          // 将参数列表加到attrs数组中
          this.addForm.attrs.push(manyInfo)
        })
        // 处理静态参数
        this.onlyTableData.forEach(item => {
          const onlyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          // 将属性列表加到attrs数组中
          this.addForm.attrs.push(onlyInfo)
        })
        // 将attrs赋值给form
        form.attrs = this.addForm.attrs
        // console.log(form)
        // 发起请求添加商品
        const { data: res } = await this.$http.post('goods/', form)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        // 跳转到商品页面
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
    // 获得三级商品分类的id
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }

  }
}
</script>

<style lang="less" scoped>
.el-steps{
  margin: 20px 40px;
  font-size: 10px;
}
.el-checkbox{
  margin-right: 5px !important;
}
img{
  width: 100% ;
}
.el-button{
  margin-top: 10px;
}
</style>
